import wx
from decimal import Decimal as Dec
import decimal
import sys
import copy

from DataTool import DataTool
from QuotaReader import QuotaReader
from SqlDict import SqlDict
from CustSearchCtrl import CustSearchCtrl

class DiaTable3add(wx.Dialog):
    ColWidth = [70, 300, 25, 50, 50, 40, 40, 40]
    ColBWidth = [80, 70, 300, 80, 200, 80, 80]
    def __init__(self, parent, title, *args, **kwargs):
        # kwargs 中 fdict 为 {'表三甲':[[]] , '表三乙':[[]] , '表三丙':[[]]}
        super().__init__(parent, -1, title)
        path = kwargs.get('path')
        imagepath = kwargs.get('imagepath')
        self.InitData(path)
        mainsizer = wx.BoxSizer(wx.VERTICAL)
        secsizer = wx.BoxSizer(wx.HORIZONTAL)
        quotasizer = wx.BoxSizer(wx.VERTICAL)
        quotaaddisizer = wx.BoxSizer(wx.VERTICAL)
        choicesizer = wx.BoxSizer(wx.HORIZONTAL)
        addbtnsizer = wx.BoxSizer(wx.VERTICAL)
        savebtnsizer = wx.BoxSizer(wx.HORIZONTAL)
        # 标题
        mainsizer.Add(secsizer, 0, flag=wx.ALL|wx.EXPAND, border=5)
        # 选择定额库
        secsizer.Add(quotasizer, 0, flag=wx.ALL|wx.EXPAND, border=5)
        quotach = wx.Choice(self, -1, choices=self.choicelistcn)
        self.Searcher = CustSearchCtrl(self)
        self.Bind(wx.EVT_CHOICE, self.OnChoice, quotach)
        # self.Bind(wx.EVT_TEXT, self.OnSearch, self.Searcher)
        self.Bind(wx.EVT_SEARCH, self.OnSearch, self.Searcher)
        quotasizer.Add(choicesizer, 0, flag=wx.ALL|wx.ALIGN_CENTER, border=0)
        choiceLbl = wx.StaticText(self, -1, "选择定额库")
        choicesizer.Add(choiceLbl,0, flag=wx.ALL|wx.ALIGN_CENTER, border=5)
        choicesizer.Add(quotach,0, flag=wx.ALL|wx.EXPAND, border=0)
        choicesizer.Add(self.Searcher,0, flag=wx.LEFT|wx.EXPAND, border=10)

        orginquota = wx.ListCtrl(self, -1, style=wx.LC_REPORT, name='定额', size=(600,300))
        quotasizer.Add(orginquota, 0, flag=wx.ALL|wx.EXPAND, border=5)
        self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelectedA, orginquota)
        self.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.OnDisSelectedA, orginquota)
        self.Bind(wx.EVT_COMMAND_LEFT_CLICK, self.OnFocusedA, orginquota)
        # 添加删除按钮
        addbtn = wx.Button(self, -1, '>', size=(30,30))
        removebtn = wx.Button(self, -1, '<', size=(30,30))
        secsizer.Add(addbtnsizer, 0, flag=wx.ALL|wx.EXPAND, border=5)
        addbtnsizer.Add((20, 20), 0, flag=wx.ALL|wx.EXPAND, border=0)
        addbtnsizer.Add((30, 30), 1, flag=wx.ALL|wx.EXPAND, border=5)
        addbtnsizer.Add(addbtn, 0, flag=wx.ALL|wx.EXPAND, border=5)
        addbtnsizer.Add((30, 30), 0, flag=wx.ALL|wx.EXPAND, border=5)
        addbtnsizer.Add(removebtn, 0, flag=wx.ALL|wx.EXPAND, border=5)
        addbtnsizer.Add((30, 30), 1, flag=wx.ALL|wx.EXPAND, border=5)
        self.Bind(wx.EVT_BUTTON, self.OnAdd, addbtn)
        self.Bind(wx.EVT_BUTTON, self.OnDel, removebtn)
        # 已选定额库
        secsizer.Add(quotaaddisizer, 0, flag=wx.ALL|wx.EXPAND, border=5)
        choiceLbl = wx.StaticText(self, -1, "已选中定额")
        quotaaddisizer.Add(choiceLbl,0, flag=wx.ALL|wx.ALIGN_CENTER, border=5)
        addquota = wx.ListCtrl(self, -1, style=wx.LC_REPORT, name='添加定额', size=(600,300))
        quotaaddisizer.Add(addquota, 0, flag=wx.ALL|wx.EXPAND, border=5)
        self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelectedB, addquota)
        self.Bind(wx.EVT_COMMAND_LEFT_CLICK, self.OnFocusedB, addquota)
        
        mainsizer.Add(wx.StaticLine(self), 0, flag=wx.ALL|wx.EXPAND, border=5)
        # 机械 仪器仪表列
        nb = wx.Notebook(self,style=wx.NB_TOP|wx.NB_FIXEDWIDTH)
        nbnamelist = ['机械', '仪器仪表', '材料']
        mech = wx.ListCtrl(nb, -1, style=wx.LC_REPORT, name='机械')
        meter = wx.ListCtrl(nb, -1, style=wx.LC_REPORT, name='仪器仪表')
        mater = wx.ListCtrl(nb, -1, style=wx.LC_REPORT, name='材料')
        listctrllist = [mech, meter, mater]
        for index, name in enumerate(nbnamelist):
            nb.AddPage(listctrllist[index], name)
        self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnCheckRelated, mech)
        self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnCheckRelated, meter)
        self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnCheckRelated, mater)
        mainsizer.Add(nb, 0, flag=wx.ALL|wx.EXPAND, border=15)

        mainsizer.Add(wx.StaticLine(self), 0, flag=wx.ALL|wx.EXPAND, border=5)
        # 保存按钮
        btnsave = wx.Button(self, -1, "保存(&S)")
        btncal = wx.Button(self, -1, "取消(&C)")
        self.Bind(wx.EVT_BUTTON, self.OnSave, btnsave)
        self.Bind(wx.EVT_BUTTON, self.OnCancel, btncal)
        mainsizer.Add(savebtnsizer, 0, flag=wx.ALL|wx.EXPAND, border=5)
        savebtnsizer.Add((140,20), 1)
        savebtnsizer.Add(btnsave,0)
        savebtnsizer.Add((140,20), 0)
        savebtnsizer.Add(btncal)
        savebtnsizer.Add((140,20), 1)

        self.InitImage(imagepath)
        self.InitListCtrl()

        self.SetSizer(mainsizer)
        mainsizer.Fit(self)
        mainsizer.SetSizeHints(self)

    def RefreshAddquota(self):
        addquota = self.FindWindowByName('添加定额')

        row = addquota.GetItemCount()
        for rowv in self.tempaddlist:
            index = addquota.InsertItem(row, rowv[0])
            for col, value in enumerate(rowv[1:]):
                addquota.SetItem(index, col+1, value)

    def CreateBitmap(self, flag=0, size=(16, 16)):
        """Create a bitmap of the platforms native checkbox. The flag
        is used to determine the checkboxes state (see wx.CONTROL_*)

        """
        bmp = wx.Bitmap(*size)
        dc = wx.MemoryDC(bmp)
        dc.SetBackground(wx.WHITE_BRUSH)
        dc.Clear()
        wx.RendererNative.Get().DrawCheckBox(self, dc,
                                             (0, 0, size[0], size[1]), flag)
        dc.SelectObject(wx.NullBitmap)
        return bmp

    def OnSave(self, event):
        self.EndModal(retCode=1)

    def OnCancel(self, event):
        self.EndModal(retCode=5101)

    def ShowModal(self):
        ret = super().ShowModal()
        if ret == 5101:
            return ret
        elif ret == 1:
            return self.adddata
        else:
            return 5101

    def OnAdd(self, event):
        
        # mech = self.FindWindowByName('机械')
        # meter = self.FindWindowByName('仪器仪表')
        idnum = 0
        for i in self.tempaddlist:
            i = copy.copy(i)
            if len(self.adddata['表三甲']) != 0:
                for j in self.adddata['表三甲']:
                    if j[0] == i[0]:
                        if int(j[-1]) >= idnum:
                            idnum = int(j[-1]) + 1
            i.append(str(idnum))
            self.adddata['表三甲'].append(i)
            # 处理 机械
            for k in self.tempB:
                if k[1] == i[0]:
                    k = copy.copy(k)
                    k.append(str(idnum))
                    self.adddata['表三乙'].append(k)
            # 处理 仪器仪表
            for k in self.tempC:
                if k[1] == i[0]:
                    k = copy.copy(k)
                    k.append(str(idnum))
                    self.adddata['表三丙'].append(k)

            idnum = 0
        # print(self.adddata['表三乙'])

        self.RefreshAddquota()
    
    def OnDel(self, event):

        addquota = self.FindWindowByName('添加定额')
        for row in self.dellist:
            addquota.DeleteItem(row)
        self.dellist = []

    def OnFocusedA(self, event):
        self.selectedflag = 'a'

    def OnFocusedB(self, event):
        self.selectedflag = 'b'

    def OnDisSelectedA(self, event):
        listctrl = event.GetEventObject()
        Oindex = event.GetIndex()
        Tindex = self.tempaddindexs.index(Oindex)
        self.tempaddindexs.remove(Oindex)
        self.tempaddlist.pop(Tindex)
        serials = []
        for i in self.tempaddindexs:
            serial = listctrl.GetItemText(i)
            serials.append(serial)
        
        self.AddBC(serials)


    def OnSelectedA(self, event):
        
        listctrl = event.GetEventObject()
        scount = listctrl.GetSelectedItemCount()
        firsts =listctrl.GetFirstSelected()
        colcount = len(self.table3acolnames)
        
        relist = []
        temp = []
        serials = []
        indexs = []
        for col in range(colcount):
            temp.append(listctrl.GetItemText(firsts, col))
        relist.append(temp)
        serial = listctrl.GetItemText(firsts)
        serials.append(serial)
        indexs.append(firsts)

        if scount > 1:
            nexts = firsts
            for i in range(scount-1):
                temp = []
                nexts = listctrl.GetNextSelected(nexts)
                for col in range(colcount):
                    temp.append(listctrl.GetItemText(nexts, col))
                relist.append(temp)
                serial = listctrl.GetItemText(nexts)
                serials.append(serial)
                indexs.append(nexts)
        
        self.tempaddlist = relist
        self.tempaddindexs = indexs
        self.AddBC(serials)
        # print(self.tempB)

    def OnSelectedB(self, event):
        
        listctrl = event.GetEventObject()
        scount = listctrl.GetSelectedItemCount()
        firsts =listctrl.GetFirstSelected()
        # 更新 dellist
        relist = []
        relist.append(firsts)

        if scount > 1:
            nexts = firsts
            for i in range(scount-1):
                nexts = listctrl.GetNextSelected(nexts)
                relist.append(nexts)
        
        self.dellist = relist
        self.SeeBC(firsts)
        self.nowaddindex = firsts

    def OnSearch(self, event):
        orginquota = self.FindWindowByName('定额')
        Data = self.NowData
        ColNum = len(self.NowData[0])
        RowNum = len(self.NowData)
        if self.LastFindLoc is None:
            StartRow = 0
            StartCol = -1
        else:
            StartRow = self.LastFindLoc[0]
            StartCol = self.LastFindLoc[1]
            if StartCol == ColNum:
                StartRow += 1
                StartCol = -1
            else:
                StartCol += 1

        for row in range(StartRow, RowNum):
            for col in range(ColNum):
                if row == StartRow and col <= StartCol:
                    continue

                if self.Searcher.IsCheckCapital:
                    SCValue = self.Searcher.GetValue()
                    CellData = Data[row][col]
                else:
                    SCValue = str(self.Searcher.GetValue()).upper()
                    CellData = str(Data[row][col]).upper()

                if self.Searcher.IsCheckAll:
                    if SCValue == CellData:
                        MatchResult = True
                    else:
                        MatchResult = False
                else:
                    if SCValue in CellData:
                        MatchResult = True
                    else:
                        MatchResult = False

                if MatchResult:
                    for i in range(orginquota.GetItemCount()):
                        if orginquota.IsSelected(i):
                            # print(i)
                            orginquota.Select(i, 0)
                    orginquota.Focus(row)
                    orginquota.Select(row)
                    self.LastFindLoc = (row, col)
                    if row == RowNum - 1 and col == ColNum -1:
                        self.LastFindLoc = None
                    return
                
                if row == RowNum - 1 and col == ColNum -1:
                    if self.LastFindLoc is None:
                        dia = wx.MessageDialog(self, '未找到匹配项',
                            caption='警告',style=wx.OK|wx.ICON_WARNING)
                        dia.ShowModal()
                        dia.Destroy()
                        return
                    else:
                        self.LastFindLoc = None
                        self.OnSearch(event)


    def OnChoice(self, event):
        self.LastFindLoc = None
        choice = event.GetEventObject()
        index = choice.GetSelection()
        pro = choice.GetString(index)
        sql = SqlDict()
        h2edict = sql.geth2edict()
        pro = h2edict[pro]
        orginquota = self.FindWindowByName('定额')
        orginquota.DeleteAllItems()
        for row, rowv in enumerate(self.data[pro]):
            index = orginquota.InsertItem(row, rowv[0])
            for col, value in enumerate(rowv[1:]):
                orginquota.SetItem(index, col+1, value)

        self.NowData = copy.deepcopy(self.data[pro])

    def OnCheckRelated(self, event):

        index = event.GetIndex()
        obj = event.GetEventObject()
        name = obj.GetName()
        img_idx = event.GetImage()
        if img_idx == 1:
            obj.SetItemImage(index, 0)
        elif img_idx == 0:
            obj.SetItemImage(index, 1)
        if len(self.tempaddlist) == 1:
            if self.selectedflag == 'a':
                if name == '机械':
                    self.tempB[index][0] = '0'
                elif name == '仪器仪表':
                    self.tempC[index][0] = '0'
            else:
                metername = obj.GetItemText(index, 4)
                idnum = self.adddata['表三甲'][self.nowaddindex][-1]
                if name == '机械':
                    changes = self.adddata['表三乙']
                elif name == '仪器仪表':
                    changes = self.adddata['表三丙']

                for i in changes:
                    if i[4] == metername and i[-1] == idnum:
                        if i[0] == '':
                            i[0] = '0'
                        else:
                            i[0] = ''
        

    def GetBC(self, serial):
        # 输入定额返回仪器仪表机械定额
        redict = {'表三乙':[], '表三丙':[]}
        for i in self.dataB:
            if serial == i[0]:
                i = copy.deepcopy(i)
                i.insert(0, '')
                redict['表三乙'].append(i)
        for i in self.dataC:
            if serial == i[0]:
                i = copy.deepcopy(i)
                i.insert(0, '')
                redict['表三丙'].append(i)
        
        return redict

    def AddBC(self, serials):
        # 输入serials刷新 机械 仪器仪表 listctrl 更新temp
        mech = self.FindWindowByName('机械')
        meter = self.FindWindowByName('仪器仪表')
        if len(serials) > 0:
            BCdict = self.GetBC(serials[0])
            self.tempB = []
            self.tempC = []
            lctrl = [mech, meter]
            ltemp = [self.tempB, self.tempC]
            cnum = 0
            for name in BCdict:
                lctrl[cnum].DeleteAllItems()
                for row, rowv in enumerate(BCdict[name]):
                    index = lctrl[cnum].InsertItem(row, rowv[0])
                    for col, value in enumerate(rowv[1:]):
                        lctrl[cnum].SetItem(index, col+1, value) 
                for serial in serials:
                    BCdict = self.GetBC(serial)
                    for row in BCdict[name]:
                        ltemp[cnum].append(row)
                cnum += 1

    def SeeBC(self, row):
        # 更新addqutoa 的 机械 仪器仪表 listctrl
        mech = self.FindWindowByName('机械')
        meter = self.FindWindowByName('仪器仪表')
        A = self.adddata['表三甲']
        B = self.adddata['表三乙']
        C = self.adddata['表三丙']
        lctrl = [mech, meter]
        ltemp = [B, C]
        serial = A[row][0]
        idnum = A[row][-1]
        for i, ctrl in enumerate(lctrl):
            ctrl.DeleteAllItems()
            for data in ltemp[i]:
                if data[1] == serial and data[-1] == idnum:
                    index = ctrl.InsertItem(row, '')
                    if data[0] == '0':
                        ctrl.SetItemImage(index, 1)
                    for col, value in enumerate(data[1:-1]):
                        ctrl.SetItem(index, col+1, value)

    def InitData(self, path):
        quota = QuotaReader(path)
        self.choicelist = quota.getpro()
        sql = SqlDict()
        e2hdict = sql.gete2hdict()
        self.data = dict()
        for i in self.choicelist:
            self.data[i] = quota.getquota(i)
        self.table3acolnames = quota.getcolnames('表三甲')
        self.table3bcolnames = quota.getcolnames('表三乙')
        self.dataB = quota.getmach()
        self.dataC = quota.getmeter()
        self.choicelistcn = [e2hdict[i] for i in self.choicelist]

        self.adddata = {'表三甲':[], '表三乙':[], '表三丙':[], }

    def InitImage(self, path):
        
        imgsz = (16, 16)
        check_image = self.CreateBitmap(wx.CONTROL_CHECKED, imgsz)
        uncheck_image = self.CreateBitmap(0, imgsz)

        mech = self.FindWindowByName('机械')
        meter = self.FindWindowByName('仪器仪表')
        mater = self.FindWindowByName('材料')
        for i in [mech, meter, mater]:
            i.imagelist = wx.ImageList(*imgsz)
            i.imagelist.Add(check_image)
            i.imagelist.Add(uncheck_image)
            i.AssignImageList(i.imagelist, wx.IMAGE_LIST_SMALL)
        self.__last_check_ = None


    def InitListCtrl(self):
        orginquota = self.FindWindowByName('定额')
        addquota = self.FindWindowByName('添加定额')
        mech = self.FindWindowByName('机械')
        meter = self.FindWindowByName('仪器仪表')

        for col, name in enumerate(self.table3acolnames):
            orginquota.InsertColumn(col, name)
            addquota.InsertColumn(col, name)
        for col, name in enumerate(self.table3bcolnames):
            mech.InsertColumn(col, name)
            meter.InsertColumn(col, name)

        for col, name in enumerate(self.table3acolnames):
            orginquota.SetColumnWidth(col, self.ColWidth[col])
            addquota.SetColumnWidth(col, self.ColWidth[col])
        for col, name in enumerate(self.table3bcolnames):
            mech.SetColumnWidth(col, self.ColBWidth[col])
            meter.SetColumnWidth(col, self.ColBWidth[col])


if __name__ == "__main__":
    import os
    class MyFrame(wx.Frame):
        def __init__(self):
            super().__init__(None, -1, 'haha', size=(200, 100))
            btn = wx.Button(self, -1, 'baba', size=(10, 10))
            self.Bind(wx.EVT_BUTTON, self.OnClick, btn)

        def OnClick(self, event):
            # modal = DiaTable2add(self, 'baba').ShowModal()
            BASE_DIR = os.path.dirname(os.path.abspath(__file__))
            path=os.path.join(BASE_DIR, 'db')
            imagepath=os.path.join(BASE_DIR, 'icon')
            imagepath=os.path.join(imagepath, 'Check')
            imagepath=os.path.join(imagepath, 'Check Icon.png')
            path=os.path.join(path, 'quota.db')
            dia = DiaTable3add(self, 'haha', path=path, imagepath=imagepath)
            modal = dia.ShowModal()
            print(modal)
            dia.Destroy()

    app = wx.App()
    MyFrame().Show()
    app.MainLoop()